import { reqAddUser } from '../../api'
let userAddForm = document.getElementById('userAddForm');
let prevImg = document.getElementById('prevImg');
let profile = document.getElementById('profile');

// 给文件上传的输入框绑定change事件 => 用于选择图片后, 自动显示预览
profile.onchange = (e) => {
  const fileReader = new FileReader()
  const file = e.target.files[0]
  fileReader.readAsDataURL(file)
  fileReader.onload = () => {
    const profile = fileReader.result
   //将预览图片的src更新
    prevImg.src = profile;
  }
}

// 绑定提交事件
userAddForm.onsubmit = async (e) => {
  // 阻止默认行为
  e.preventDefault()
  // 收集表单数据
  const formData = new FormData(userAddForm)
  // 提交添加用户请求
  const result = await reqAddUser(formData)
  if (result.code===2000) {
    // 成功后跳转到用户列表页
    window.location = '/users.html'
  } else {
    alert(result.message)
  }
}